﻿using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;

namespace Gonte.Web
{
    public static class HttpRequestExtensions
    {
        /// <summary>
        /// Retrieves the ISO culture user language as a string
        /// </summary>
        /// <param name="request">The HTTP request</param>
        /// <returns>The ISO defined language as a string or null if none was found</returns>
        public static string GetLanguage(this HttpRequest request)
        {
            if (request.UserLanguages == null)
            {
                return null;
            }

            return request.UserLanguages[0];
        }

        /// <summary>
        /// Returns the user culture info that corresponds to the request
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static CultureInfo GetCulture(this HttpRequest request)
        {
            string language = request.GetLanguage();

            if (language != null)
            {
                return new CultureInfo(language);
            }

            return CultureInfo.InvariantCulture;
        }

        /// <summary>
        /// Retrieves the full ISO defined language as a string
        /// </summary>
        /// <param name="request">The HTTP request</param>
        /// <param name="defaultLanguage">The default language to return in case there is none set</param>
        /// <returns>The full ISO defined language as a string</returns>
        public static string GetLanguage(this HttpRequest request, IEnumerable<string> supportedLanguages, string defaultLanguage = "en-US")
        {
            if (request.UserLanguages == null)
            {
                return defaultLanguage;
            }

            string language =  request.UserLanguages[0];

            if (language == null
                || !supportedLanguages.Contains(language))
            {
                return defaultLanguage;
            }

            return language;
        }

        /// <summary>
        /// Retrieves the short ISO defined language as a string
        /// </summary>
        /// <param name="request">The HTTP request</param>
        /// <param name="defaultLanguage">The default language to return in case there is none set</param>
        /// <returns>The short ISO defined language as a string</returns>
        public static string GetShortLanguage(this HttpRequest request, IEnumerable<string> supportedLanguages, string defaultLanguage = "en")
        {
            return GetLanguage(request, supportedLanguages, defaultLanguage).Substring(0, 2);
        }
    }
}
